package com.xes.recognitiondemo;

import android.annotation.TargetApi;
import android.content.ContentUris;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.support.annotation.CheckResult;

/**
 * @author wl
 * @since 2016/11/09 11:17
 */
public class UriUtils {

    /**
     * 根据文件uri获取到对应的path路径
     * @param context context
     * @param uri uri
     * @return path
     */
    public static String parseFileUriToPath(Context context, Uri uri) {
        String path;
        if (Build.VERSION.SDK_INT >= 19) {
            //4.4及以上系统使用这个方法处理图片
            path = parseUriOnKitKat(context, uri);
        } else {
            //4.4以下系统使用这个方法处理图片
            path = parseUriBeforeKitKat(context, uri);
        }
        return path;
    }

    //4.4及以上系统使用这个方法处理图片
    @TargetApi(19)
    private static String parseUriOnKitKat(Context context, Uri uri) {
        String path = uri.getPath();
        if (DocumentsContract.isDocumentUri(context, uri)) {
            //如果是document类型的Uri,则通过document id处理
            String docId = DocumentsContract.getDocumentId(uri);
            if (isMediaDocument(uri)) {
                String id = docId.split(":")[1];  //解析出数字格式的id
                String selection = MediaStore.Images.Media._ID + "=" + id;
                path = getContentPath(context, MediaStore.Images.Media.EXTERNAL_CONTENT_URI, selection);
            } else if (isDownloadsDocument(uri)) {
                Uri contentUri = ContentUris.withAppendedId(
                        Uri.parse("content://downloads/public_downloads"), Long.valueOf(docId));
                path = getContentPath(context, contentUri, null);
            }
        } else if ("content".equalsIgnoreCase(uri.getScheme())) {
            //如果不是document类型的Uri,则使用普通方式处理
            path = getContentPath(context, uri, null);
        }
        return path;
    }

    //4.4以下系统使用这个方法处理图片
    private static String parseUriBeforeKitKat(Context context, Uri uri) {
        return getContentPath(context, uri, null);
    }

    private static String getContentPath(Context context, Uri uri, String selection) {
        String column = "_data";
        String path = null;
        //通过Uri和selection来获取真实的图片路径
        Cursor cursor = context.getContentResolver().query(uri, new String[] {column}, selection, null, null);
        if (cursor != null) {
            if (cursor.moveToFirst()) {
                path = cursor.getString(cursor.getColumnIndex(column));
            }
            cursor.close();
        }
        return path;
    }

    /**
     * 发送一个uri交给系统的activity manager去处理
     * @param context context
     * @param uri uri
     * @return true-系统正确处理了，false-没有找到合适的activity去处理
     */
    @CheckResult
    public static boolean deliveryUriToSystem(Context context, Uri uri) {
        try {
            Intent intent = new Intent(Intent.ACTION_VIEW, uri);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(intent);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is ExternalStorageProvider.
     */
    public static boolean isExternalStorageDocument(Uri uri) {
        return "com.android.externalstorage.documents".equals(uri.getAuthority());
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is DownloadsProvider.
     */
    public static boolean isDownloadsDocument(Uri uri) {
        return "com.android.providers.downloads.documents".equals(uri.getAuthority());
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is MediaProvider.
     */
    public static boolean isMediaDocument(Uri uri) {
        return "com.android.providers.media.documents".equals(uri.getAuthority());
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is Google Photos.
     */
    public static boolean isGooglePhotosUri(Uri uri) {
        return "com.google.android.apps.photos.content".equals(uri.getAuthority());
    }

}
